﻿using CsvHelper;
using CsvHelper.Configuration;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TaskbarClock;

namespace CSVTools
{
    public partial class CSVMainForm : Form
    {
        private bool tableHeadRb = true;
        private List<dynamic> csvList = new List<dynamic>();
        private string exportFileName = string.Empty;
        public CSVMainForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 选择文件按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelectSourceFileBtn_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog dialog = new OpenFileDialog();
                dialog.Filter = "CSV文件(*.csv)|*.csv";

                string gg = System.Configuration.ConfigurationManager.AppSettings["StoresConfigPath"];
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    this.SelectSourceText.Text = dialog.FileName;              

                    //1.获取文件的原始编码
                    Encoding encoding = GetEncoding.GetJpEncoding(dialog.FileName);
                    if (encoding == Encoding.GetEncoding(932))
                    {
                        this.UTF_8_CheckBox.Checked = false;
                        this.CP932_CheckBox.Checked = false;
                        this.SHIFT_JIS_CheckBox.Checked = true;
                    }
                    else
                    {
                        this.UTF_8_CheckBox.Checked = true;
                        this.CP932_CheckBox.Checked = false;
                        this.SHIFT_JIS_CheckBox.Checked = false;
                    }
                    //2.换行符
                    bool rnflag = GetEncoding.GetRNFlag(dialog.FileName, GetFileEncode());
                    if (rnflag)
                    {
                        this.NCheckBox.Checked = false;
                        this.RNCheckBox.Checked = true;
                    }
                    else
                    {
                        this.NCheckBox.Checked = true;
                        this.RNCheckBox.Checked = false;
                    }
                    //3 是否有双引号
                    if (GetEncoding.GetYinHaoFlag(dialog.FileName, GetFileEncode()))
                    {
                        this.shuangyinhao.Checked = true;
                    }
                    else 
                    {
                        this.shuangyinhao.Checked = false;
                    }
                }
            }
            catch (Exception ex)
            {
                this.CreateCSVBtn.Enabled = true;
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 选择目标文件就
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SetFolderBtn_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dilog = new FolderBrowserDialog();
            dilog.Description = "请选择文件夹";
            if (dilog.ShowDialog() == DialogResult.OK || dilog.ShowDialog() == DialogResult.Yes)
            {
                this.TargetFolderText.Text = dilog.SelectedPath;
            }
        }

        /// <summary>
        /// 生成按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CreateCSVBtn_Click(object sender, EventArgs e)
        {
            this.CreateCSVBtn.Enabled = false;
            try
            {
                //读
                string filename = this.SelectSourceText.Text;
                FileInfo sourcefileinfo = new FileInfo(filename);
                if (!sourcefileinfo.Exists) 
                {
                    MessageBox.Show("文件不存在");
                    return;
                }
                var config = new CsvConfiguration(CultureInfo.InvariantCulture)
                {
                    HasHeaderRecord = this.TableHeadRb.Checked
                };
                using (StreamReader reader = new StreamReader(filename, GetFileEncode()))
                {
                    using (var csv1 = new CsvReader(reader, config))
                    {
                        exportFileName = sourcefileinfo.Name;
                        csvList = csv1.GetRecords<dynamic>().ToList();
                    }
                }
                #region   验证

                if (csvList == null || csvList.Count == 0)
                {
                    MessageBox.Show("源文件数据为空！", "提示", MessageBoxButtons.OK);
                    this.CreateCSVBtn.Enabled = true;
                    return;
                }

                var shopCodesStr = this.ShopCodesText.Text.Trim();
                if (string.IsNullOrEmpty(shopCodesStr))
                {
                    MessageBox.Show("要导出的店铺编码不可以为空！", "提示", MessageBoxButtons.OK);
                    this.CreateCSVBtn.Enabled = true;
                    return;
                }

                //要导出的店铺集合
                var shopList = shopCodesStr.Replace("，", ",").Split(',');
                if (shopList == null || shopList.Length == 0)
                {
                    MessageBox.Show("要导出的店铺编码不可以为空！", "提示", MessageBoxButtons.OK);
                    this.CreateCSVBtn.Enabled = true;
                    return;
                }

                //是否有表头
                var isHasTableHead = this.TableHeadRb.Checked;

                var shopCodeColNum = this.CSVRowsCountText.Text.Trim();
                if (string.IsNullOrEmpty(shopCodeColNum))
                {
                    MessageBox.Show("店铺编号CSV中的行号不可以为空！", "提示", MessageBoxButtons.OK);
                    this.CreateCSVBtn.Enabled = true;
                    return;
                }

                var targetFolderPath = this.TargetFolderText.Text.Trim();
                if (string.IsNullOrEmpty(targetFolderPath))
                {
                    MessageBox.Show("目标文件夹不可以为空！", "提示", MessageBoxButtons.OK);
                    this.CreateCSVBtn.Enabled = true;
                    return;
                }
                #endregion


                #region    执行导出

                //是否有表头
                var csvHeadCols = this.TableHeadRb.Checked ? csvList[0] : null;

                var shopCsvFile = targetFolderPath + $@"\{DateTime.Now.ToString("yyyyMMddHHmm")}_{exportFileName}";
                using (var writer = new StreamWriter(shopCsvFile)) 
                {
                    //如果有表头
                    if (csvHeadCols != null)
                    {
                        var obj = csvHeadCols as System.Dynamic.ExpandoObject;
                        var fileds = obj.Select(a => a.Key).ToList();
                        int idx = 0;
                        foreach (var field in fileds)
                        {
                            writer.Write(HandleLineBreak(field));
                            if (++idx != fileds.Count)
                            {
                                writer.Write(",");
                            }
                        }

                        if (this.NCheckBox.Checked)
                            writer.Write("\n");
                        else
                            writer.Write("\r\n");

                        //有表头 去掉表头
                        csvList.RemoveAt(0);
                    }

                    foreach (var item in csvList)
                    {
                        var obj = item as System.Dynamic.ExpandoObject;

                        if (obj != null)
                        {
                            //var keys = obj.Select(a => a.Key).ToList();
                            var values = obj.Select(a => a.Value).ToList();
                            if (!shopList.Contains(values[int.Parse(shopCodeColNum)].ToString()))
                                continue;

                            int idx = 0;
                            foreach (var val in values)
                            {
                                writer.Write(HandleLineBreak(val.ToString()));
                                if (++idx != values.Count) 
                                {
                                    writer.Write(",");
                                }
                            }

                            if (this.NCheckBox.Checked)
                                writer.Write("\n");
                            else
                                writer.Write("\r\n");
                        }
                    }

                }

                #endregion

                this.CreateCSVBtn.Enabled = true;
            }
            catch (Exception ex)
            {
                this.CreateCSVBtn.Enabled = true;
                MessageBox.Show(ex.Message);
            }
        }

        private void TableHeadRb_Click(object sender, EventArgs e)
        {
            if (tableHeadRb)
            {
                this.TableHeadRb.Checked = false;
                tableHeadRb = false;
            }
            else
            {
                this.TableHeadRb.Checked = true;
                tableHeadRb = true;
            }
        }

        private void UTF_8_CheckBox_Click(object sender, EventArgs e)
        {
            if (this.UTF_8_CheckBox.Checked)
            {
                this.SHIFT_JIS_CheckBox.Checked = false;
                this.CP932_CheckBox.Checked = false;
            }
            else
                if (this.SHIFT_JIS_CheckBox.Checked == false && this.CP932_CheckBox.Checked == false)
                this.UTF_8_CheckBox.Checked = true;
        }

        private void SHIFT_JIS_CheckBox_Click(object sender, EventArgs e)
        {
            if (this.SHIFT_JIS_CheckBox.Checked)
            {
                this.UTF_8_CheckBox.Checked = false;
                this.CP932_CheckBox.Checked = false;
            }
            else
                if (this.UTF_8_CheckBox.Checked == false && this.CP932_CheckBox.Checked == false)
                this.SHIFT_JIS_CheckBox.Checked = true;
        }

        private void CP932_CheckBox_Click(object sender, EventArgs e)
        {
            if (this.CP932_CheckBox.Checked)
            {
                this.SHIFT_JIS_CheckBox.Checked = false;
                this.UTF_8_CheckBox.Checked = false;
            }
            else
                if (this.SHIFT_JIS_CheckBox.Checked == false && this.UTF_8_CheckBox.Checked == false)
                this.CP932_CheckBox.Checked = true;
        }

        private void NCheckBox_Click(object sender, EventArgs e)
        {
            if (this.NCheckBox.Checked)
                this.RNCheckBox.Checked = false;
            else
                if (this.RNCheckBox.Checked == false)
                this.NCheckBox.Checked = true;
        }

        private void RNCheckBox_Click(object sender, EventArgs e)
        {
            if (this.RNCheckBox.Checked)
                this.NCheckBox.Checked = false;
            else
                if (this.NCheckBox.Checked == false)
                this.RNCheckBox.Checked = true;
        }
        private string HandleLineBreak(string val)
        {
            if (this.shuangyinhao.Checked)
            {
                return "\""+val+"\"";
            }
            else 
            {
                return val;
            }
            
        }
        private Encoding GetFileEncode()
        {
            if (this.UTF_8_CheckBox.Checked)
                return Encoding.GetEncoding("UTF-8");

            if (this.SHIFT_JIS_CheckBox.Checked)
                return Encoding.GetEncoding("SHIFT-JIS");

            if (this.CP932_CheckBox.Checked)
                return Encoding.GetEncoding("CP932");

            throw new Exception("未知的编码格式");
        }
    }
}
